package models

import (
	"log"
	"math/rand"
	"time"
)

// 初始化商品数据
func InitProducts() {
    // 获取现有商品
    products, err := GetProducts()
    if err != nil {
        log.Fatal("Error fetching products: ", err)
    }

    // 如果没有商品数据，则添加默认商品
    if len(products) == 0 {
        log.Println("No products found. Adding default products.")

        // 自定义20个商品数据
        productsToAdd := []Product{
            {Name: "家用电器", Price: 120.0, Quantity: 10},
            {Name: "家居", Price: 150.0, Quantity: 20},
            {Name: "家具", Price: 10.0, Quantity: 30},
			{Name: "家具", Price: 20.0, Quantity: 45},
			{Name: "家装", Price: 30.0, Quantity: 55},
			{Name: "厨具", Price: 40.0, Quantity: 65},
			{Name: "电脑", Price: 50.0, Quantity: 75},
			{Name: "文具", Price: 60.0, Quantity: 85},
			{Name: "美妆", Price: 70.0, Quantity: 95},
			{Name: "个护清洁", Price: 80.0, Quantity: 105},
			{Name: "宠物", Price: 80.0, Quantity: 115},
			{Name: "男装", Price: 90.0, Quantity: 125},
			{Name: "女装", Price: 100.0, Quantity: 135},
			{Name: "童装", Price: 110.0, Quantity: 145},
			{Name: "女鞋", Price: 120.0, Quantity: 155},
			{Name: "箱包", Price: 130.0, Quantity: 165},
			{Name: "钟表", Price: 140.0, Quantity: 175},
			{Name: "珠宝", Price: 150.0, Quantity: 185},
			{Name: "男鞋", Price: 160.0, Quantity: 195},
			{Name: "户外", Price: 170.0, Quantity: 205},
			{Name: "运动", Price: 180.0, Quantity: 215},
			{Name: "食品", Price: 190.0, Quantity: 225},
			{Name: "酒类", Price: 200.0, Quantity: 235},
			{Name: "生鲜", Price: 210.0, Quantity: 245},
			{Name: "特产", Price: 220.0, Quantity: 255},
			{Name: "母婴", Price: 230.0, Quantity: 265},
			{Name: "玩具乐器", Price: 240.0, Quantity: 275},

            // 其他自定义商品...
        }

        for _, product := range productsToAdd {
            AddProduct(product)
        }
    }
}


// 初始化用户数据
func InitUsers() {
    // 获取现有用户
    users, err := GetUsers()
    if err != nil {
        log.Fatal("Error fetching users: ", err)
    }

    // 如果没有用户数据，则添加默认用户
    if len(users) == 0 {
        log.Println("No users found. Adding default users.")

        // 自定义10个用户数据
        usersToAdd := []User{
            {Username: "JohnDoe", Password: "password123", Phonenumber: "12345678901", Email: "johndoe@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
            {Username: "JaneSmith", Password: "password456", Phonenumber: "12345678902", Email: "janesmith@qq.com", Balance: 100.0, CouponCount: 5, IsMember: false},
			{Username: "xiaoming", Password: "password123", Phonenumber: "12345678903", Email: "xiaoming@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
			{Username: "xiaohuang", Password: "password123", Phonenumber: "12345678904", Email: "xiaohuang@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
			{Username: "xiaohong", Password: "password123", Phonenumber: "12345678905", Email: "xiaohong@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
			{Username: "xiaolan", Password: "password123", Phonenumber: "12345678906", Email: "jxiaolan@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
			{Username: "xiaolv", Password: "password123", Phonenumber: "12345678907", Email: "xiaolv@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
			{Username: "xiaozi", Password: "password123", Phonenumber: "12345678908", Email: "xiaozi@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
			{Username: "xiaofen", Password: "password123", Phonenumber: "12345678909", Email: "xiaofen@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},
			{Username: "xiaoniu", Password: "password123", Phonenumber: "12345678910", Email: "xiaoniu@qq.com", Balance: 500.0, CouponCount: 10, IsMember: true},

            // 其他自定义用户...
        }

        for _, user := range usersToAdd {
            AddUser(user)
        }
    }
}


// 初始化订单数据
func InitOrders() {
    users, err := GetUsers()
    if err != nil {
        log.Fatal("Error fetching users: ", err)
    }

    products, err := GetProducts()
    if err != nil {
        log.Fatal("Error fetching products: ", err)
    }

    if len(users) == 0 || len(products) == 0 {
        log.Println("No users or products found. Cannot add orders.")
        return
    }

    log.Println("Inserting orders for users.")

    // 为每个用户插入自定义订单
    for _, user := range users {
        for i := 1; i <= 3; i++ {
            randProductIndex := rand.Intn(len(products)) // 随机选择商品
            product := products[randProductIndex]

            // 你可以为订单自定义数量、总金额等
            order := Order{
                UserID:      user.ID,
                ProductID:   product.ID,
                ProductName: product.Name,
                Quantity:    rand.Intn(5) + 1,  // 随机选择数量
                TotalAmount: product.Price * float64(rand.Intn(5)+1),
                Status:      "Pending",         // 可自定义状态
                OrderDate:   time.Now(),
            }

            _, err := AddOrder(order)
            if err != nil {
                log.Printf("Error adding order for user %d: %v", user.ID, err)
            } 
        }
    }
}



// 初始化购物车数据
func InitCart() {
    users, err := GetUsers()
    if err != nil {
        log.Fatal("Error fetching users: ", err)
    }

    products, err := GetProducts()
    if err != nil {
        log.Fatal("Error fetching products: ", err)
    }

    if len(users) == 0 || len(products) == 0 {
        log.Println("No users or products found. Cannot add cart items.")
        return
    }

    log.Println("Inserting cart items for users.")

    // 为每个用户生成购物车数据
    for _, user := range users {
        for i := 1; i <= 4; i++ {
            randProductIndex := rand.Intn(len(products)) // 随机选择商品
            product := products[randProductIndex]

            // 随机选择购物车数量（1-5之间）
            quantity := rand.Intn(5) + 1

            cartItem := CartItem{
                UserID:      user.ID,
                ProductID:   product.ID,
                ProductName: product.Name,
                Quantity:    quantity,
                Price:       product.Price,
            }

            err := AddToCart(cartItem)
            if err != nil {
                log.Printf("Error adding item to cart for user %d: %v", user.ID, err)
            } 
        }
    }
}


// 初始化支付信息数据
func InitPayments() {
    users, err := GetUsers()
    if err != nil {
        log.Fatal("Error fetching users: ", err)
    }

    orders, err := GetOrders()
    if err != nil {
        log.Fatal("Error fetching orders: ", err)
    }

    if len(users) == 0 || len(orders) == 0 {
        log.Println("No users or orders found. Cannot add payment information.")
        return
    }

    log.Println("Inserting payment information for users.")

    for _, user := range users {
        userOrders := getOrdersByUserID(user.ID, orders)

        for i, order := range userOrders {
            if i >= 2 { // 每个用户最多生成2个支付信息
                break
            }

            paymentStatus := "Pending"
            if rand.Intn(2) == 0 {
                paymentStatus = "Completed"
            }

            paymentMethods := []string{"Credit Card", "PayPal", "Bank Transfer"}
            paymentMethod := paymentMethods[rand.Intn(len(paymentMethods))]

            amount := order.TotalAmount

            payment := Payment{
                OrderID:       order.ID,
                PaymentMethod: paymentMethod,
                PaymentStatus: paymentStatus,
                PaymentDate:   time.Now(),
                Amount:        amount,
            }

            _, err := AddPayment(payment)
            if err != nil {
                log.Printf("Error adding payment for order %d: %v", order.ID, err)
            } 
        }
    }
}


// 获取用户的所有订单
func getOrdersByUserID(userID int, orders []Order) []Order {
	var userOrders []Order
	for _, order := range orders {
		if order.UserID == userID {
			userOrders = append(userOrders, order)
		}
	}
	return userOrders
}

// 初始化所有数据（商品、用户、订单、购物车、支付信息等）
func InitData() {
	InitProducts()  // 初始化商品数据
	InitUsers()     // 初始化用户数据
	InitOrders()    // 初始化订单数据
	InitCart()      // 初始化购物车数据
	InitPayments()  // 初始化支付信息数据
}
